package com.platform.hjt.from.service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.snaker.engine.entity.Order;
import org.springframework.stereotype.Service;

import com.hjt.tools.dao.Page;
import com.hjt.tools.dao.PropertyFilter;
import com.hjt.tools.date.DateCreator;
import com.platform.hjt.base.controller.ReturnBody;
import com.platform.hjt.base.costant.ErrorCode;
import com.platform.hjt.base.service.BaseService;
import com.platform.hjt.flow.service.SnakerEngineFacets;
import com.platform.hjt.from.controller.param.OrderQZParam;
import com.platform.hjt.from.dao.FromQjOrderDAO;
import com.platform.hjt.from.dao.FromQjOrderDetailDAO;
import com.platform.hjt.from.model.FromQjOrder;
import com.platform.hjt.from.model.FromQjOrderDetail;
import com.platform.hjt.from.model.MoldeQjFrom;

@Service
public class FromQjOrderService extends BaseService{

	@Resource
	private FromQjOrderDAO fromQjOrderDAO;
	@Resource
	private FromQjOrderDetailDAO fromQjOrderDetailDAO;
	@Resource
	private SnakerEngineFacets facets;
	@Resource
	private FromQjOrderService fromQjOrderService;
	
	
	public ReturnBody saveFromQjOrder(FromQjOrder fromQjOrder){
		if(StringUtils.isNotBlank(fromQjOrder.getQjOrderId())){
			fromQjOrderDAO.updatePerproties(fromQjOrder);
			return  new ReturnBody(true, "更新成功");
		}else{
			 fromQjOrderDAO.saveJ(fromQjOrder);
			return  new ReturnBody(true, "添加成功");
		}
	}
	
	public ReturnBody saveFromQjOrder(MoldeQjFrom moldeQjFrom){
		moldeQjFrom.getFromQjOrder().setSysCompanyInfo(getSessionSysCompanyInfo());
		moldeQjFrom.getFromQjOrder().setSysUserInfo(getSessionUserInfo());
		moldeQjFrom.getFromQjOrder().setCreateTime(DateCreator.getCurrentTime());
		moldeQjFrom.getFromQjOrder().setIsDel(false);
		moldeQjFrom.getFromQjOrder().setAuditingTotalPrice(0.0);	//默认审核总价为0
		
		FromQjOrder fromQjOrder = fromQjOrderDAO.saveJ(moldeQjFrom.getFromQjOrder());
		
		List<FromQjOrderDetail> fromQjOrderDetailList = moldeQjFrom.getFromQjOrderDetailList();
		
		double totalPrice = 0;
		//计算总价
		for(FromQjOrderDetail fod : fromQjOrderDetailList){
			totalPrice += fod.getCount() * fod.getPrice();
			
			fod.setIsIn(false);
			fod.setIsOut(false);
			fod.setIsProduce(false);
			fod.setIsAllow(false);
			fod.setFromQjOrder(fromQjOrder);
			fromQjOrderDetailDAO.save(fod);
		}
		
		Order order  = facets.startAndExecute(moldeQjFrom.getFromQjOrder().getProcessId(), getSessionUserInfo().getSysUserInfoId(), null);
		
		/*order.setOrderNo(DateCreator.createDate("NoSymbolTime"));
		facets.getEngine().order().updateOrder(order);*/
		
		fromQjOrder.setOrderTotalPrice(totalPrice);
		fromQjOrder.setProcessOrderId(order.getId());
		
		return  new ReturnBody(true, "添加成功");
	}
	
	public ReturnBody handleDirectorAuditing(String processId, String orderId, String taskId){
		String status = getRequest().getParameter("status");
		if(status.equals("-1")){	//扭转上节点
			facets.getEngine().executeAndJumpTask(taskId, getSessionUserInfo().getSysUserInfoId(), null, null);
			return new ReturnBody(true, "流程已回退");
			
		} else if(status.equals("1")){
			String id = getRequest().getParameter("ids");
			String oid = getRequest().getParameter("oid");

			String delHql = "update FromQjOrderDetail t set t.isAllow=false where t.fromQjOrder.qjOrderId=?";
			fromQjOrderDetailDAO.batchExecute(delHql, oid);

			String detailHql = "update FromQjOrderDetail t set t.isAllow = true where t.qjOrderDetailId in (:ids)";
			String[] ids = id.split(",");
			List<String> idList = Arrays.asList(ids);
			
			fromQjOrderDetailDAO.createQuery(detailHql).setParameterList("ids", idList).executeUpdate();
			
			String orderSql = "update from_qj_order t set t.auditing_total_price = (select sum(det.price*det.count) from from_qj_order_detail det where det.qj_order_detail_id in (:ids)) where t.qj_order_id =:oid";
			fromQjOrderDAO.createSQLQuery(orderSql).setParameterList("ids", ids).setString("oid", oid).executeUpdate();
			facets.getEngine().executeTask(taskId, getSessionUserInfo().getSysUserInfoId());
		}
		return new ReturnBody(true, "审核完成");
	}
	
	public ReturnBody handleScpd(String processId, String orderId, String taskId){
		String status = getRequest().getParameter("status");
		if(status.equals("-1")){	//扭转上节点
			facets.getEngine().executeAndJumpTask(taskId, getSessionUserInfo().getSysUserInfoId(), null, null);
			return new ReturnBody(true, "流程已回退");
			
		} else if(status.equals("1")){
			String id = getRequest().getParameter("ids");
			String oid = getRequest().getParameter("oid");

			String delHql = "update FromQjOrderDetail t set t.isProduce=false where t.fromQjOrder.qjOrderId=?";
			fromQjOrderDetailDAO.batchExecute(delHql, oid);
			
			String[] ids = id.split(",");
			List<String> idList = Arrays.asList(ids);
			String detailHql = "update FromQjOrderDetail t set t.isProduce = true where t.qjOrderDetailId in (:ids)";
			fromQjOrderDetailDAO.createQuery(detailHql).setParameterList("ids", idList).executeUpdate();
			
			String orderSql = "update from_qj_order t set t.auditing_total_price = (select sum(det.price*det.count) from from_qj_order_detail det where det.qj_order_detail_id in (:ids)) where t.qj_order_id =:oid";
			fromQjOrderDAO.createSQLQuery(orderSql).setParameterList("ids", ids).setString("oid", oid).executeUpdate();
			facets.getEngine().executeTask(taskId, getSessionUserInfo().getSysUserInfoId());
		}
		return new ReturnBody(true, "审核完成");
	}

	public ReturnBody handleScbmsh(OrderQZParam orderQZParam, String processId, String orderId, String taskId){
		String status = getRequest().getParameter("status");
		if(status.equals("-1")){	//扭转上节点
			facets.getEngine().executeAndJumpTask(taskId, getSessionUserInfo().getSysUserInfoId(), null, null);
			return new ReturnBody(true, "流程已回退");
			
		} else if(status.equals("1")){
			
			for(FromQjOrderDetail detail : orderQZParam.getFromQjOrderDetailList()){
				fromQjOrderDetailDAO.updatePerproties(detail);
			}
			
			facets.getEngine().executeTask(taskId, getSessionUserInfo().getSysUserInfoId());
		}
		return new ReturnBody(true, "审核完成");
	}
	
	public ReturnBody handleproductAssociation(String processId, String orderId, String taskId){
		String status = getRequest().getParameter("status");
		if(status.equals("-1")){	//扭转上节点
			facets.getEngine().executeAndJumpTask(taskId, getSessionUserInfo().getSysUserInfoId(), null, null);
			return new ReturnBody(true, "流程已回退");
			
		} else if(status.equals("1")){
			
			String[] ids = getRequest().getParameterValues("ids");
			String[] colorCodes = getRequest().getParameterValues("colorCode");

			if(ids.length != colorCodes.length){
				return new ReturnBody(false, "错误代码：" + ErrorCode.DataError.getKey() + ",请联系管理员。");
			}
			
			String detailHql = "update FromQjOrderDetail t set t.colorCode = ? where t.qjOrderDetailId = ? ";
			for(int i=0, len=ids.length; i<len; i++){
				fromQjOrderDetailDAO.batchExecute(detailHql, colorCodes[i], ids[i] );
			}
			
			facets.getEngine().executeTask(taskId, getSessionUserInfo().getSysUserInfoId());
		}
		return new ReturnBody(true, "关联完成");
	}
	
	
	public ReturnBody handleJieshu(String processId, String orderId, String taskId){
		
		FromQjOrder fromQjOrder = fromQjOrderService.getFromQjOrder("processOrderId", orderId);
		
		Map<String, Object>map = new HashMap<String, Object>();
		map.put("fromQjOrder.qjOrderId", fromQjOrder.getQjOrderId());
		map.put("isProduce", true);
		map.put("isOut", false);
		List<FromQjOrderDetail> list = fromQjOrderService.getfromQjOrderDetailList(map);
		
		if(list.size()>0){
			//如还有未出库的东西，则跳动入库节点
			facets.getEngine().executeAndJumpTask(taskId, getSessionUserInfo().getSysUserInfoId(), null, "ruku");
		} else{
			facets.getEngine().executeTask(taskId, getSessionUserInfo().getSysUserInfoId());
		}
		
		return  new ReturnBody(true, "操作成功");
	}
	
	public ReturnBody delFromQjOrder(FromQjOrder fromQjOrder){
		fromQjOrder.setIsDel(true);
		fromQjOrderDAO.updatePerproties(fromQjOrder);
		return  new ReturnBody(true, "删除成功");
	}
	
	public Page<FromQjOrder> getFromQjOrderList(Page<FromQjOrder> page, List<PropertyFilter> propertyFilterList){
		return fromQjOrderDAO.findPage(page, propertyFilterList);
	}
	
	public List<FromQjOrder> getFromQjOrderList(List<PropertyFilter> filters){
		return fromQjOrderDAO.find(filters);
	}
	
	public FromQjOrder getFromQjOrder(List<PropertyFilter> filters){
		return fromQjOrderDAO.findUniqueBy(filters);
	}
	
	public FromQjOrder getFromQjOrder(String propertyName, Object value){
		return fromQjOrderDAO.findUniqueBy(propertyName, value);
	}
	
	public List<FromQjOrderDetail> getfromQjOrderDetailList(String propertyName, Object value){
		return fromQjOrderDetailDAO.findBy(propertyName, value);
	}
	
	public List<FromQjOrderDetail> getfromQjOrderDetailList(Map<String, Object> map){
		return fromQjOrderDetailDAO.findBy(map);
	}
	
}
